<template>
  <p-row type="flex" class="mf-compile-rule-wrap">
    <p-col class="mf-compile-rule-left">
      <p-input-search placeholder="请输入" v-model="SearchValue" />
      <MesMfRulesTree :SearchValue="SearchValue" @onSelect="selectItems" />
    </p-col>
    <p-col flex="1" class="mf-compile-rule-right">
      <component :is="currentView" />
      <p-table
        v-show="!currentView"
        ref="table"
        size="middle"
        bordered
        rowKey="key"
        :pagination="false"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :loading="loading"
        @change="onSelectChange"
        :customRow="clickThenSelect"
      >
        <!-- 更改内容 -->
        <template slot="changeContent" slot-scope="text,row">
          <input type="text" @blur="changeContent(row)" v-model="row.content">
        </template>
        <!-- 是否开关插槽 -->
        <template slot="status" slot-scope="text, row">
          <p-switch
            :checked-children="text === 0 || text === null ? '开' : ''"
            :un-checked-children="text === 1 ? '关' : ''"
            :default-checked="text === 0 ? true : false"
            @change="onChange(row)"
          />
        </template>
      </p-table>
    </p-col>
  </p-row>
  
</template>

<script>
import Vue from "vue";
import MesMfRulesTree from "@/components/Privately/MesMfRulesTree.vue";
import { postAction, getAction, deleteAction, putAction } from "@/api/manage";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";

export default {
  name: "MesMfSchedulingRules",

  components: {
    MesMfRulesTree,
    ProduceException: () => import('./produceException'),
    ExceptionReceiver: () => import('./exceptionReceiver'),
  },
  data() {
    return {
      SearchValue: "", //搜索内容
      //tableInfo
      EnhanceJS: "",
      cgButtonLinkList: [],
      cgButtonList: [],
      dataSource: [],
      title: "", //存表名
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "id",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "规则编码",
          dataIndex: "code",
          key: "code",
          // width: "15%",
          align: "center",
          scopedSlots: { customRender: "code" },
        },
        {
          title: "规则名称",
          dataIndex: "name",
          key: "name",
          // width: "40%",
          align: "center",
          scopedSlots: { customRender: "name" },
        },
        {
          title: "内容",
          dataIndex: "content",
          // width: "40%",
          align: "center",
          scopedSlots: { customRender: "changeContent" },
        },

        {
          title: "是否启动",
          dataIndex: "status",
          key: "status",
          align: "center",
          scopedSlots: { customRender: "status" },
        },
        {
          title: "操作",
          dataIndex: "operation",
          align: "center",
          scopedSlots: { customRender: "operation" },
        },
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      //生产规则列表
      query: {
        code: "",
        content: "",
        keyword: "",
        limit: "",
        name: "",
        pageNo: "",
        ruleld: "",
        scope: "",
        status: "",
      },
      //编辑规则
      editVisible: false,
      url: {
        //获取生产规则列表
        list: "/mes-manufacture/mfRuleDetails/list",
        //调用修改生产规则
        revisionOfProductionRules: "/mes-manufacture/mfRuleDetails",
      },
      currentView: ''
    };
  },
  created() {
    this.initColumns();
    this.setdefColumns();
    // this.loadData();
  },

  methods: {
    //规则信息Table
    selectItems(data) {
      if (data.key === 7 || data.key === 8) {
        this.currentView = data.key === 7 ? 'produce-exception' : 'exception-receiver'
        return
      }
      this.currentView = ''
      this.dataSource = [];
      getAction(this.url.list, { ruleId: data.key }).then((res) => {
        if (res.code === 0) {
          //  this.$message.success(res.msg);
          this.dataSource = res.data;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
      });
    },
    //规则开关
    onChange(row) {
      let info = {
        status: !row.status,
      };
      if (info.status) info.status = 1;
      else info.status = 0;
      const info2 = Object.assign(row, info);
      //调用修改生产规则
      putAction(this.url.revisionOfProductionRules, info2).then((res) => {
        if (res.code == 0) {
          return this.$message.success("启动规则状态成功");
        }
        this.$message.warning("启动规则状态失败");
      });
    },
    changeContent(data){
      putAction(this.url.revisionOfProductionRules, data).then((res) => {
        if (res.code == 0) {
          return this.$message.success("修改则状态成功");
        }
        this.$message.warning("修改规则失败");
      });
    },


    //编辑规则页面的隐藏与展示
    handleEdit() {
      this.editVisible = true;
    },
    handleOk() {
      this.editVisible = false;
    },
    handleNotOk() {
      this.editVisible = false;
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },

    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
    setdefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[arrLength]["fixed"] = "right";
        this.columns[0]["fixed"] = "left";
        this.columns[1]["fixed"] = "left";
      }
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },

    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectedMainId = "";
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0];
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      // var params = this.getQueryParams(); //查询条件
      this.loading = true;
      getAction(this.url.list, this.query).then((res) => {
        if (res.success) {
          this.dataSource = res.data;
          // this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.id, [record]);
          },
        },
      };
    },
  },
};
</script>

<style lang="less" scoped>
input{text-align: center;outline: none;border: none;}

.mf-compile-rule {
  &-wrap {
    height: 100%;
    overflow: hidden;
  }

  &-left,
  &-right {
    height: 100%;
    padding: 20px;
    overflow-y: auto;
  }

  &-left {
    width: 330px;
    padding: 20px;
    border-right: 1px solid #eee;
    overflow-x: hidden;
  }

  &-right {
    min-width: 0;
    min-height: 0;
    overflow-x: auto;
  }
}
</style>
